﻿using System.Collections.ObjectModel;
using Avalonia.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SimpleToDoList.Models;
using SimpleToDoList.Services;

namespace SimpleToDoList.ViewModels;

public partial class MainViewModel : ViewModelBase
{
    private string? _newItemContent;
    public string? NewItemContent
    {
        get => _newItemContent;
        set
        {
            if (SetProperty(ref _newItemContent, value))
            {
                AddItemCommand.NotifyCanExecuteChanged();
            }
        }
    }
    public ObservableCollection<ToDoItemViewModel> ToDoItems { get; } = new ObservableCollection<ToDoItemViewModel>();
    public IRelayCommand AddItemCommand { get; }
    public IRelayCommand<ToDoItemViewModel> RemoveItemCommand { get; }
    public MainViewModel()
    {
        AddItemCommand = new RelayCommand(AddItem, CanAddItem);
        RemoveItemCommand = new RelayCommand<ToDoItemViewModel>(RemoveItem);

        if (Design.IsDesignMode)
        {
            ToDoItems = new ObservableCollection<ToDoItemViewModel>(
                new[]
                {
                    new ToDoItemViewModel() { Content = "Hello" },
                    new ToDoItemViewModel() { Content = "Avalonia", IsChecked = true }
                }
            );
        }
    }

    private void AddItem()
    {
        ToDoItems.Add(new ToDoItemViewModel() { Content = NewItemContent });
        NewItemContent = null;
    }

    private bool CanAddItem() => !string.IsNullOrWhiteSpace(NewItemContent);

    private void RemoveItem(ToDoItemViewModel? item)
    {
        if (item == null)
            return;
        ToDoItems.Remove(item);
    }
}
